package com.thd.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

@Component
public class PreLogGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    private Logger logger = LoggerFactory.getLogger(PreLogGatewayFilterFactory.class.getName());
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return ((exchange, chain) -> {
            logger.info("自定义过滤器工厂 - 日志打印参数：{},{}", config.getName(), config.getValue());

            // 修改请求
            ServerHttpRequest modifiedRequest = exchange.getRequest()
                    .mutate()
                    .build();

            // 修改exchange
            ServerWebExchange modifiedExchange = exchange.mutate()
                    .request(modifiedRequest)
                    .build();

            // 传递给下一个过滤器处理
            return chain.filter(modifiedExchange);
        });
    }
}
